package org.rendao.biz.web;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.jws.HandlerChain;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.rendao.biz.service.QuestionService;
import org.rendao.config.ConfigurationService;
import org.rendao.model.CommonSummary;
import org.rendao.model.FusionchartData;
import org.rendao.utils.ReportUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping(value = "/report")
public class ReportController {

	private static final Logger logger = Logger
			.getLogger(ReportController.class);

	@Autowired
	private QuestionService questionService;

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}
	
	@Autowired
	private ConfigurationService config;
	
	public void setConfig(ConfigurationService config) {
		this.config = config;
	}


	@RequestMapping(value = "/fusioncharts/first_index_summary", method = RequestMethod.GET)
	@ResponseBody
	public FusionchartData getFirstIndexSummary(HttpServletResponse response) {

		logger.debug("get first index summary ...");

		String caption = config.getConfig(config.FC_COLUMN3D_CAPTION);
		String xLabel = config.getConfig(config.FC_COLUMN3D_XAXISNAME);
		String yLabel = config.getConfig(config.FC_COLUMN3D_YAXISNAME);
		
		logger.debug("Caption: " + caption);
		logger.debug("X Axis Label: " + xLabel);
		logger.debug("Y Axis Label: " + yLabel);
		
		List<CommonSummary> list = questionService.getFirstIndexSummary();

		FusionchartData data = ReportUtils.getFusionchartData(list, caption, xLabel, yLabel);
		return data;
		
		/*
		response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition","attachment;filename=data.xml");
		String xml = ReportUtils.getFusionchartDataXml(list);
		StringBuffer sb = new StringBuffer();
		sb.append(xml);
		try {
			InputStream in = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
			ServletOutputStream out = response.getOutputStream();
			byte[] outputByte = new byte[4096];
			int c = in.read(outputByte, 0, 4096);
			while(c != -1) {
				out.write(outputByte, 0, c);
				c = in.read(outputByte, 0, 4096);
			}
			in.close();
			out.flush();
			out.close();
		} catch (IOException e) {
			throw new RuntimeException(e);
		} 
		*/
	}

}
